﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace DBShell
{
    class Util
    {
        public static char[] REPLACEARRAY = { ' ', '(', ')', '[', ']', '\t', '>', '<', '=' };
        public static char[] TOREPLACEARRAY = { '^', '(', ')', '[', ']', '\t', '>', '<', '=' };

        public static string[] RESERVEWORD = { "delete","select", "from", "where", "create", "table", "drop", "insert", "update", "set", "and", "or", "like", "is","into","values" };

        public Util()
        {
        }
        public static string ReplaceSpace(string cmd)
        {
            string newcmd = "";
            bool replaceMode = false;
            for (int i = 0; i < cmd.Length; i++)
            {
                if (cmd[i] == '\'')
                {
                    if ((i > 0 && cmd[i - 1] != '\\') || (i == 0))
                    {
                        replaceMode = !replaceMode;
                    }
                }
                if (REPLACEARRAY.Contains(cmd[i]) && replaceMode)
                {
                    newcmd += TOREPLACEARRAY[REPLACEARRAY.ToList().IndexOf(cmd[i])];
                }
                else
                {
                    newcmd += cmd[i];
                }
            }
            return newcmd;
        }

        public static string Standazation(string cmd)
        {
            char[] split = { ' ' };
            string[] str = cmd.Split(split, StringSplitOptions.RemoveEmptyEntries);
            bool replaceMode = true;
            for (int i = 0; i < str.Length; i++)
            {
                if (str[i].IndexOf('\'') > -1)
                {
                    if (str[i].IndexOf('\'') != str[i].LastIndexOf('\''))
                    {
                        replaceMode = !replaceMode;
                    }
                }
                else
                {
                    if (RESERVEWORD.Contains(str[i].ToLower()) && replaceMode)
                    {
                        str[i] = str[i].ToUpper();
                    }
                }
            }
            string newcmd = "";
            foreach (string i in str)
            {
                newcmd += i;
                newcmd += ' ';
            }
            return newcmd.Trim();
        }
    }
}
